package com.huluobo.mvvm_base.mvvm.base.view;

import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.huluobo.mvvm_base.mvvm.base.model.BaseRepo;
import com.huluobo.mvvm_base.mvvm.base.viewmodel.BaseViewModel;
import com.huluobo.mvvm_base.mvvm.event.CustomEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by LC on 2024/2/22.
 * ViewDataBinding 是视图数据绑定,是MVVM简化的一种方式
 */
public abstract class BaseMVVMActivity<VDB extends ViewDataBinding, VM extends BaseViewModel>
        extends AppCompatActivity {
    //数据视图绑定
    protected VDB dataBinding;

    //对应的ViewModel
    protected VM viewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //1.绑定视图
        dataBinding = DataBindingUtil.setContentView(this, getLayoutId());
        //2.实例化对应的ViewModel
        viewModel = new ViewModelProvider(this).get(getViewModel());
        //3.初始化控件
        initView();
        //4.初始化数据
        initData();
        //5.注册EventBus
        EventBus.getDefault().register(this);
        //设置沉浸式状态栏
        getWindow().setStatusBarColor(Color.TRANSPARENT);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveEvent(CustomEvent event) {
        //校验事件是否合法
        if (event == null || event.getTarget() == null) return;

        //目标页校验,对比事件中的目标类名,如果等于当前的类名,则处理事件
        if (event.getTarget().equals(getClass().getSimpleName())) {
            //处理事件
            handEvent(event);
        }

    }

    public void handEvent(CustomEvent event) {
        //TODO 让子类去处理,不写抽象的原因是,不是每个Activity都必须要处理事件
    }

    protected abstract void initData();

    protected abstract void initView();

    protected abstract Class<VM> getViewModel();//LoginViewModel.class

    protected abstract int getLayoutId();
}
